package net.courier.remoting.provider.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import net.courier.remoting.protocol.ResponseDatagram;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResultReceiveHandler extends ChannelInboundMessageHandlerAdapter<ResponseDatagram> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ResultReceiveHandler.class);
	
	private final ClientPromise clientPromise;

	public ResultReceiveHandler(ClientPromise clientPromise) {
		this.clientPromise = clientPromise;
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, ResponseDatagram msg) throws Exception {
		clientPromise.setSuccess(msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		LOGGER.warn("处理消息发生异常", cause);
		clientPromise.setFailure(cause);
		ctx.close();
	}
	
	public ClientPromise getClientPromise() {
		return clientPromise;
	}

}
